#include "lcmusic.h"
#include "sys_app.h"
#include "msg_manager.h"

lcmusic_app_data_t* lcmusic_app_data = NULL;

lcmusic_app_data_t* lcmusic_get_data(void)
{
    return lcmusic_app_data;
}

static int lcmusic_init(void)
{
    ESP_LOGI(TAG, "%s", __func__);

    if (lcmusic_app_data) {
        ESP_LOGE(TAG, "%s: already initialized", __func__);
        return -1;
    }

    lcmusic_app_data = malloc(sizeof(lcmusic_app_data_t));
    if (!lcmusic_app_data) {
        ESP_LOGE(TAG, "%s: malloc failed", __func__);
        return -1;
    }
    memset(lcmusic_app_data, 0, sizeof(lcmusic_app_data_t));

    lcmusic_view_init();

    lcmusic_iterator_init(lcmusic_app_data);

    lcmusic_media_init(lcmusic_app_data);

    return 0;
}

static int lcmusic_exit(void)
{
    ESP_LOGI(TAG, "%s", __func__);

    lcmusic_view_exit();
    
    lcmusic_stop_play(lcmusic_app_data);

    lcmusic_iterator_deinit(lcmusic_app_data);

    lcmusic_media_deinit(lcmusic_app_data);

    if (lcmusic_app_data) {
        free(lcmusic_app_data);
        lcmusic_app_data = NULL;
    }

    return 0;
}

void lcmusic_main_loop(void *arg)
{
    struct app_msg* msg = NULL;

    while (sys_get_cur_app() == SYS_APP_LCMUSIC) {
        if (msg_manager_receive_msg(&msg, portMAX_DELAY)) {
            ESP_LOGI(TAG, "%s: receive msg type: %d, cmd: %d, value: %08x", __func__, msg->type, msg->cmd, msg->value);
            switch (msg->type) {
                case MSG_INIT_APP:
                    if (lcmusic_init()) {
                        sys_app_quit(sys_get_cur_app());
                    }
                break;

                case MSG_EXIT_APP:
                    lcmusic_exit();
                break;

                default:
                    ESP_LOGE(TAG, "%s: unknown msg type: %d", __func__, msg->type);
                break;
            }
            msg_manager_receive_exit(msg);
        }
    }
}
